import { assign, forEach } from "lodash"
import dispatchRequest from "./dispatchRequest"
import InterceptorManager from "./InterceptorManager"

function Axios(instanceConfig) {
	this.defaultConfig = instanceConfig
	this.interceptors = {
		request: new InterceptorManager(),
		response: new InterceptorManager()
	}
}

Axios.prototype.request = function request(config) {
	// 合并配置
	config = assign({}, this.defaultConfig || {}, config)

	let chain = [dispatchRequest, undefined]
	this.interceptors.request.forEach(function forEachRequestInterceptor({ fulfilled, rejected }) {
		chain.unshift(fulfilled, rejected)
	})
	this.interceptors.response.forEach(function forEachResponseInterceptor({ fulfilled, rejected }) {
		chain.push(fulfilled, rejected)
	})

	let promise = Promise.resolve(config)
	while (chain.length) {
		promise = promise.then(chain.shift(), chain.shift())
	}
	// Promise.resolve(config).then((config) => {
	// 	return (this.interceptors.request.fulfilled(), this.interceptors.request.reject())
	// }).then(config => {
	// 	return (dispatchRequest(), undefined)
	// }).then(response => {
	// 	return (this.interceptors.response.fulfilled(), this.interceptors.response.reject())
	// })
	return promise;
}

forEach(['get', 'delete'], (val) => {
	Axios.prototype[val] = function buildMethodNoData(url, config) {
		return this.request(assign(config || {}, {
			url: url,
			method: val
		}))
	}
})

forEach(['put', 'post'], (val) => {
	Axios.prototype[val] = function buildMethodWithData(url, data, config) {
		return this.request(assign(config || {}, {
			url: url,
			data: data,
			method: val
		}))
	}
})

export default Axios;